/* eslint-disable react/no-children-prop */
/* eslint-disable react/no-array-index-key */
import React from 'react';

import { ReactComponent as ChevroneLeft } from '@/assets/images/profile/ChevroneLeft.svg';
import { AuthApi } from '@/entities/auth/api';
import { checkPassword, restorePassword } from '@/entities/auth/model/actions';
import { getAuthEmail, getIsCorrectPassword } from '@/entities/auth/model/selectors';
import { ModalContext } from '@/shared/context/ModalContext';
import { Modals } from '@/shared/interfaces';
import { useMetaTag } from '@/shared/lib/hooks';
import { useAppDispatch, useAppSelector } from '@/shared/store';
import { Button, ButtonVariants, FlexWrapper, Input, Modal, Snackbar } from '@/shared/ui';
import { ModalPage } from '@/widgets/ModalPage';
import { useSnackbar } from 'notistack';
import { useWindowSize } from 'usehooks-ts';

import cs from './ChangePassword.module.scss';

const authApi = new AuthApi();

export const ChangePassword = () => {
  const [currentPassword, setCurrentPassword] = React.useState<string>('');
  const [newPassword, setNewPassword] = React.useState<string>('');
  const [isHiddenCurrent, setIsHiddenCurrent] = React.useState(true);
  const [isHiddenNew, setIsHiddenNew] = React.useState(true);
  const [changed, setChanged] = React.useState(false);
  const [inFocus, setFocus] = React.useState(false);
  const { enqueueSnackbar } = useSnackbar();
  const isCorrect = useAppSelector(getIsCorrectPassword);
  const dispatch = useAppDispatch();
  const [open, setIsOpen] = React.useState(false);
  const { width } = useWindowSize();
  const handleCheckRightPassword = (password: string) => {
    if (inFocus) {
      return;
    }
    dispatch(checkPassword({ password })).then(() => {
      setChanged(false);
    });
  };

  const handleChangeCurrent = (e: any) => {
    setCurrentPassword(e.target.value);
    setChanged(true);
  };
  const { closeModal, openModal, setData, data } = React.useContext(ModalContext);

  const email = useAppSelector(getAuthEmail);
  const actualEmail = email;
  useMetaTag(open, '#999999');
  const handleGetNewPassword = () => {
    dispatch(restorePassword({ email: actualEmail })).then(() => {
      openModal(Modals.SuccessPassword);
    });
  };
  const editPassword = () => {
    authApi.changeOldPassword({ oldPassword: currentPassword, newPassword }).then(() => {
      enqueueSnackbar('Пароль изменен', {
        variant: 'success',
        content: (key, message) => <Snackbar id={key} message={message} size="md" variant="success" />,
      });
      closeModal();
    });
  };
  React.useEffect(() => {
    const debounceTimeout = setTimeout(() => {
      handleCheckRightPassword(currentPassword);
    }, 500);
    return () => clearTimeout(debounceTimeout);
  }, [currentPassword, dispatch, inFocus]);
  React.useEffect(() => {
    if (data?.first) {
      setCurrentPassword(data?.first);
    }

    if (data?.second) {
      setNewPassword(data?.second);
    }
  }, []);
  return (
    <>
      <ModalPage className={cs.modal} handleClose={closeModal} isMobile={false} isOpen>
        <div className={cs.passes}>
          <h2 className={cs.title}>Изменить пароль</h2>
          <div className={cs.block}>
            <div className={cs.newPass}>
              <span className={cs.blockTitle}>Текущий пароль</span>
              <Button
                className={cs.forgot}
                onClick={() => {
                  if (width > 1024) {
                    closeModal();
                    setData(() => ({ first: currentPassword, second: newPassword }));
                    openModal(Modals.GetNewPassword);
                  } else {
                    setIsOpen(true);
                  }
                }}
                variant={ButtonVariants.Link}
              >
                Забыли пароль?
              </Button>
            </div>
            <FlexWrapper>
              <Input
                accepted={isCorrect !== null && isCorrect && !changed && currentPassword.length > 0}
                autoComplete="new-password"
                autoFocus={width > 768 && currentPassword.length === 0}
                data-testid="input-old-password"
                handleHidePassword={() => setIsHiddenCurrent(false)}
                handleShowPassword={() => setIsHiddenCurrent(true)}
                hidden={isHiddenCurrent}
                htmlFor="currentPassword"
                isNotAccepted={isCorrect !== null && !isCorrect && !changed && currentPassword.length > 0}
                isNotAcceptedText="Неверный пароль"
                isPasswordField
                onBlur={() => setFocus(false)}
                onChange={handleChangeCurrent}
                onFocus={() => setFocus(true)}
                type={isHiddenCurrent ? 'password' : 'text'}
                value={currentPassword}
              />
            </FlexWrapper>
          </div>
          <div className={cs.block}>
            <span className={cs.blockTitle}>Новый пароль</span>
            <FlexWrapper>
              <Input
                data-testid="input-new-password"
                handleHidePassword={() => setIsHiddenNew(false)}
                handleShowPassword={() => setIsHiddenNew(true)}
                hidden={isHiddenNew}
                htmlFor="newPassword"
                isAutoFocus={width > 768 && newPassword.length === 0 && currentPassword.length !== 0}
                isNotAcceptedText="Минимум 6 символов"
                isPasswordField
                isPasswordFieldReg
                onChange={(e) => setNewPassword(e.target.value)}
                type={isHiddenNew ? 'password' : 'text'}
                value={newPassword}
              />
            </FlexWrapper>
          </div>
          <div className={cs.button}>
            <Button
              children="Изменить"
              disabled={
                !newPassword || !currentPassword || newPassword.length < 6 || (isCorrect !== null && !isCorrect)
              }
              onClick={editPassword}
              variant={ButtonVariants.Primary}
            />
          </div>
        </div>
      </ModalPage>
      <Modal className={cs.modal} isMobile={false} isOpen={open} onCloseClick={() => setIsOpen(false)} zIndex={1100}>
        <span className={cs.back}>
          <ChevroneLeft />
        </span>
        <div className={cs.passes}>
          <h2 className={cs.title}>Получить пароль</h2>
          <p className={cs.block}>
            Отправим новый пароль <br />
            на {actualEmail}
          </p>
        </div>
        <div className={cs.button}>
          <Button
            children="Получить"
            disabled={false}
            onClick={handleGetNewPassword}
            variant={ButtonVariants.Primary}
          />
        </div>
      </Modal>
    </>
  );
};
